package com.zqs.controller;


import com.zqs.controller.ex.FileUploadException;
import com.zqs.service.ex.*;
import com.zqs.utils.JsonResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

/**
 * 异常规划返回数据基类
 */
@RestController
public class BaseController {

    public static final int OK = 200;

    @ExceptionHandler({ServiceException.class, FileUploadException.class})
    public JsonResult<Void> handelException(Throwable throwable){
        JsonResult<Void> result = new JsonResult<>();
        if (throwable instanceof InsertException){
            result.setState(4000);
            result.setMessage("插入时异常!");
        }else if(throwable instanceof UsernameDuplicatedException){
            result.setState(4001);
            result.setMessage("用户名被占用!");
        }else if(throwable instanceof UsernameErrorException){
            result.setState(4002);
            result.setMessage("用户名错误!");
        }else if(throwable instanceof PasswordErrorException){
            result.setState(4003);
//            result.setMessage("密码错误!");
        }else if(throwable instanceof KaptchaException){
            result.setState(4004);
            result.setMessage("验证码错误!");
        }
        return result;
    }

    public Integer getSessionUid(HttpSession session){
        Integer uid = (Integer) session.getAttribute("uid");
        return uid;
    }

    public String  getSessionUsername(HttpSession session){
        String username = (String) session.getAttribute("username");
        return username;
    }
}
